<template>
  <a-modal v-model:open="form.visible" width="1200px" @ok="onOk()" :destroyOnClose="true" >
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row" v-privilege="'goods:query'">
        <a-form-item label="商品分类" class="smart-query-form-item">
          <category-tree
            width="150px"
            v-model:value="queryForm.categoryId"
            placeholder="请选择商品分类"
            :categoryType="CATEGORY_TYPE_ENUM.GOODS.value"
          />
        </a-form-item>

        <a-form-item label="物料名称" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.searchWord" placeholder="商品名称" />
        </a-form-item>
        <a-form-item label="物料名称" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.searchWord" placeholder="商品名称" />
        </a-form-item>


        <a-form-item label="产地" name="place" class="smart-query-form-item">
          <DictSelect :dict-code="DICT_CODE_ENUM.GOODS_PLACE" v-model:value="queryForm.place" width="120px" />
        </a-form-item>
        <a-form-item label="物料状态" name="goodsStatus" class="smart-query-form-item">
          <SmartEnumSelect enum-name="GOODS_STATUS_ENUM" v-model:value="queryForm.goodsStatus" width="160px" />
        </a-form-item>
        <a-form-item label="快速筛选" class="smart-query-form-item">
          <a-radio-group v-model:value="queryForm.shelvesFlag" @change="onSearch">
            <a-radio-button :value="undefined">全部</a-radio-button>
            <a-radio-button :value="'true'">上架</a-radio-button>
            <a-radio-button :value="'false'">下架</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button-group>
            <a-button type="primary" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" >
      <!---------- 表格操作行 begin ----------->

      <!---------- 表格操作行 end ----------->
      <a-table
        size="small"
        :dataSource="form.lista"
        :columns="columns"
        rowKey="goodsId"
        :scroll="{ x: 1000, y: 600 }"
        :pagination="false"
        :showSorterTooltip="false"
        @change="onChange"
        @resizeColumn="handleResizeColumn"
        :row-selection="{ selectedRowKeys: form.selectDocEntrys, onChange: onSelectChange }"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'goodsName'">
            {{ text }}
          </template>
          <template v-if="column.dataIndex === 'place'">
            <DictLabel :dict-code="DICT_CODE_ENUM.GOODS_PLACE" :data-value="text" />
          </template>
          <template v-if="column.dataIndex === 'remark'">
            <span>{{ text ? text : '' }}</span>
          </template>

          <template v-if="column.dataIndex === 'goodsStatus'">
            <span>{{ $smartEnumPlugin.getDescByValue('GOODS_STATUS_ENUM', text) }}</span>
          </template>

          <template v-if="column.dataIndex === 'shelvesFlag'">
            <span>{{ text ? '上架' : '下架' }}</span>
          </template>
          <template v-if="column.dataIndex === 'source'">
            <span>{{ text ? '自制' : '外购' }}</span>
          </template>
        </template>
      </a-table>

      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total) => `共${total}条`"
        />
      </div>
    </a-card>
  </a-modal>
</template>
<script setup>
  import GoodsFormModal from '/src/views/business/erp/bas/components/goods-form-modal.vue';
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/src/components/framework/smart-loading';
  import { goodsApi } from '/src/api/business/goods/goods-api';
  import { PAGE_SIZE_OPTIONS } from '/src/constants/common-const';
  import CategoryTree from '/src/components/business/category-tree-select/index.vue';
  import { CATEGORY_TYPE_ENUM } from '/src/constants/business/erp/category-const';
  import { smartSentry } from '/src/lib/smart-sentry';
  import TableOperator from '/src/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/src/constants/support/table-id-const';
  import DictSelect from '/src/components/support/dict-select/index.vue';
  import SmartEnumSelect from '/src/components/framework/smart-enum-select/index.vue';
  import _ from 'lodash';
  import SmartHeaderCell from '/src/components/support/table-header-cell/index.vue';
  import { DICT_CODE_ENUM } from '/src/constants/support/dict-const.js';
  import DictLabel from '/src/components/support/dict-label/index.vue';
  import { unitApi } from '/src/api/business/erp/unit-api.js';

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '商品分类',
      dataIndex: 'categoryName',
      resizable: true,
      filterOptions: {
        type: 'category-tree',
        key: 'categoryId',
        categoryType: CATEGORY_TYPE_ENUM.GOODS.value,
      },
      width: 200,
    },
    {
      title: '商品编码',
      dataIndex: 'goodsNum',
      resizable: true,
      align: 'left',
      width: 230,
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      resizable: true,
      align: 'left',
      width: 230,
      ellipsis: true,
    },
    {
      title: '商品状态',
      dataIndex: 'goodsStatus',
      resizable: true,
      width: 150,
    },
    {
      title: '价格',
      dataIndex: 'price',
      align: 'center',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'shelvesFlag',
      align: 'center',
      width: 80,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 100,
      align: 'center',
    },
    {
      title: '规格',
      dataIndex: 'specs',
      width: 200,
      align: 'left',
    },
    {
      title: '仓库编码',
      dataIndex: 'stoId',
      width: 200,
    },

    {
      title: '仓库名称',
      dataIndex: 'stoName',
      width: 200,
    },

    {
      title: '来源',
      dataIndex: 'source',
      width: 150,
    },
    {
      title: 'BOM编码',
      dataIndex: 'bomId',
      width: 150,
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const form = reactive({
    visible: false,
    total: 0,
    lista: [],
    selectDocEntrys: [],
    row:[]
  });

  const queryFormState = {
    categoryId: undefined,
    searchWord: '',
    goodsStatus: undefined,
    place: undefined,
    shelvesFlag: undefined,
    goodsType: undefined,
    pageNum: 1,
    pageSize: 20,
    sortItemList: [],
  };
  // 查询表单form
  const queryForm = reactive(_.cloneDeep(queryFormState));
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  function handleResizeColumn(w, col) {
    columns.value.forEach((item) => {
      if (item.dataIndex === col.dataIndex) {
        item.width = Math.floor(w);
        // 拖动宽度标识
        item.dragAndDropFlag = true;
      }
    });
  }

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, _.cloneDeep(queryFormState));
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  function queryData() {
    tableLoading.value = true;
    goodsApi
      .queryGoodsList(queryForm)
      .then((res) => {
        form.lista = res.data.list;
        form.total = res.data.total;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }

  onMounted(queryData);

  // ---------------------------- 添加/修改 ----------------------------
  const formModal = ref();

  function addGoods(goodsData) {
    formModal.value.showDrawer(goodsData);
  }

  // ---------------------------- 单个删除 ----------------------------

  function deleteGoods(goodsData) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除【' + goodsData.goodsName + '】吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        singleDelete(goodsData);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function singleDelete(goodsData) {
    try {
      SmartLoading.show();
      await goodsApi.deleteGoods(goodsData.goodsId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys,row) {
    form.selectDocEntrys = selectedRowKeys;
    form.row = row

  }

  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中商品吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        batchDelete();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function batchDelete() {
    try {
      SmartLoading.show();
      await goodsApi.batchDelete(selectedRowKeyList.value);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ------------------------------- 导出和导入 ---------------------------------
  // 导入弹窗
  const importModalShowFlag = ref(false);

  const fileList = ref([]);

  // 显示导入
  function showImportModal() {
    fileList.value = [];
    importModalShowFlag.value = true;
  }

  // 关闭 导入
  function hideImportModal() {
    importModalShowFlag.value = false;
  }

  function handleChange() {}

  function handleDrop() {}

  function handleRemove(file) {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  }

  function beforeUpload(file) {
    fileList.value = [...(fileList.value || []), file];
    return false;
  }

  function downloadExcel() {
    window.open('https://smartadmin.vip/cdn/%E5%95%86%E5%93%81%E6%A8%A1%E6%9D%BF.xls');
  }

  async function onImportGoods() {
    const formData = new FormData();
    fileList.value.forEach((file) => {
      formData.append('file', file.originFileObj);
    });

    SmartLoading.show();
    try {
      let res = await goodsApi.importGoods(formData);
      message.success(res.msg);
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  async function onExportGoods() {
    await goodsApi.exportGoods();
  }

  function onChange(pagination, filters, sorter, { action }) {
    if (action === 'sort') {
      const { order, field } = sorter;
      let column = camelToUnderscore(field);
      let findIndex = queryForm.sortItemList.findIndex((e) => e.column === column);
      if (findIndex !== -1) {
        queryForm.sortItemList.splice(findIndex, 1);
      }
      if (order) {
        let isAsc = order !== 'ascend';
        queryForm.sortItemList.push({
          column,
          isAsc,
        });
      }
      queryData();
    }
  }

  function camelToUnderscore(str) {
    return str.replace(/([A-Z])/g, '_$1').toLowerCase();
  }

  const emit = defineEmits(['onOk']);

  function onOk() {
    emit('onOk', form.row);
    form.visible = false;
  }

  function showModal(item) {
    queryData();
    form.visible = true;
  }

  defineExpose({
    showModal,
  });
</script>
